
import logging
import signal
import socketserver
import sys
import threading
import re

from app import create_app
from configs import config
from utils.decorator import async_func
from utils.handler_tools import msg_tool, command_tool

logger = logging.getLogger(__name__)


class ThreadTCPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        msg = msg_tool.receive(self, self.request.recv(config.BYTE_LIMIT).strip())
        if not msg or msg['token'] > config.CLIENT_MAX_TOKEN:
            return
        command_tool.start(self, msg)

    def __str__(self):
        return f'{self.client_address[0]}:{self.client_address[-1]}'


class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True


def close(signo, frame):
    print('TCP server exit...')
    sys.exit(1)


@async_func
def tcp_start(server):
    with server:
        for s in range(config.MAX_SERVER_THREAD_NUM):
            server_thread = threading.Thread(target=server.serve_forever, daemon=True)
            server_thread.start()

        logger.info(f'server start, host: {config.SERVER_HOST}, port: {config.SERVER_PORT}')
        server.serve_forever()


